package com.bbva.generico.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import oracle.sql.BLOB;

public class UtilClass {

	/**
	 * Metodo para insertar espacios en blanco
	 * 
	 * @param cantidad
	 *            Indicar la cantidad de espacios en blanco.
	 * @return Devuelve una cadena de espacios vacios.
	 */
	public static String setSpaceWhite(int cantidad) {
		String space = "";
		for (int i = 1; i <= cantidad; i++) {
			space = space + " ";
		}
		return space;
	}

	public static void main(String[] args) {
		String variable = setSpaceWhite(4);
		System.out.println("---> resultado: " + variable);
	}

	/**
	 * 
	 * @param inputBinaryFileName Ruta y nombre del file de entrada.
	 * @param outputBinaryFileName2 Ruta y nombre del file de salida.
	 * @param image Imagen obtenido de la consulta.
	 * @throws IOException
	 * @throws SQLException
	 */
	public void readBLOBToFileStream(String inputBinaryFileName, String outputBinaryFileName2, byte[] image) throws IOException, SQLException {
		
		File inputBinaryFile = null;
		File outputBinaryFile2 = null;
		
		inputBinaryFile = new File(inputBinaryFileName);
		if (!inputBinaryFile.exists()) {
			throw new IOException("File not found. " + inputBinaryFileName);
		}
		
		FileOutputStream outputFileOutputStream = null;
		InputStream blobInputStream = null;
		int bytesRead = 0;
		int totBytesRead = 0;
		int totBytesWritten = 0;

		try {
			outputBinaryFile2 = new File(outputBinaryFileName2);
			outputFileOutputStream = new FileOutputStream(outputBinaryFile2);
			// Will use a Java InputStream object to read data from a BLOB (can
			// also be used for a CLOB) object. In this example, we will use an
			// InputStream to read data from a BLOB.

			while ((bytesRead = blobInputStream.read(image)) != -1) {
				// Loop through while reading a chunk of data from the BLOB
				// column using an InputStream. This data will be stored
				// in a temporary buffer that will be written to disk.
				outputFileOutputStream.write(image, 0, bytesRead);
				totBytesRead += bytesRead;
				totBytesWritten += bytesRead;
			}

			outputFileOutputStream.close();
			blobInputStream.close();
			System.out.println("==========================================================\n"
							+ "  INPUT STREAMS METHOD\n"
							+ "==========================================================\n"
							+ "Wrote BLOB column data to file "
							+ outputBinaryFile2.getName()
							+ ".\n"
							+ totBytesRead
							+ " bytes read.\n"
							+ totBytesWritten
							+ " bytes written.\n");

		} catch (IOException e) {
			System.out.println("Caught I/O Exception: (Write BLOB value to file - Streams Method).");
			e.printStackTrace();
			throw e;
		}
	}

}
